package com.yiwei.jmx.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.AddressAddV3Bean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.info.InfoCallBack;
import com.yiwei.jmx.info.PhoneInfo;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.view.SelectMenuDilaog;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class IdentityContactActivity extends BaseActivity implements OnAddressSelectedListener {

    @BindView(R.id.txt_title)
    TextView txtTitle;

    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.txt_relative_one)
    TextView txtRelativeOne;
    @BindView(R.id.layout_relative_one)
    LinearLayout layoutRelativeOne;
    @BindView(R.id.txt_name_one)
    TextView txtNameOne;
    @BindView(R.id.txt_phone_one)
    TextView txtPhoneOne;
    @BindView(R.id.btn_contact_one)
    ImageView btnContactOne;
    @BindView(R.id.txt_relative_two)
    TextView txtRelativeTwo;
    @BindView(R.id.layout_relative_two)
    LinearLayout layoutRelativeTwo;
    @BindView(R.id.txt_name_two)
    TextView txtNameTwo;
    @BindView(R.id.txt_phone_two)
    TextView txtPhoneTwo;
    @BindView(R.id.cb_check)
    ImageView cbCheck;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.btn_contact_two)
    ImageView btnContactTwo;
    @BindView(R.id.txt_area)
    TextView txtArea;
    @BindView(R.id.layout_area)
    LinearLayout layoutArea;
    @BindView(R.id.edit_address)
    EditText editAddress;

    private Unbinder unbiner;
    private int selectRelative = 0;
    private int selectContact = 0;
    private SelectMenuDilaog selectMenuDilaog;
    private SelectMenuTipsDilaog selectMenuTipsDilaog;
    private boolean isAgree = false;
    private List<Map<String, String>> contactList;
    private List<Map<String, String>> callLogList;
    private List<Map<String, String>> appList;
    private List<Map<String, String>> smsList;
    private PhoneInfo phoneInfo;
    private BottomDialog bottomDialog;
    private AddressAddV3Bean.AddressBean addressInfo;
    private String province;
    private String city;
    private String area;
    private AddressAddV3Bean.RelativesBean relativesBean1;
    private AddressAddV3Bean.RelativesBean relativesBean2;
    private List<AddressAddV3Bean.RelativesBean> relativesBeen;
    private List<String> dataOne;
    private List<String> dataTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_identity);
        initWebViewBar();
        setBarClick();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(this);

        addressInfo = new AddressAddV3Bean.AddressBean();
        addressInfo.name = UserInfoGlobal.getRealName();
        addressInfo.phone = UserInfoGlobal.getMobile();

        relativesBeen = new ArrayList<>();
        relativesBean1 = new AddressAddV3Bean.RelativesBean();
        relativesBean2 = new AddressAddV3Bean.RelativesBean();
        relativesBeen.add(relativesBean1);
        relativesBeen.add(relativesBean2);

        phoneInfo = new PhoneInfo(this);  //实例化通讯录
        selectMenuTipsDilaog = new SelectMenuTipsDilaog(this).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
            @Override
            public void onLeft() {
                finish();
            }

            @Override
            public void onRight() {
                selectMenuTipsDilaog.dismiss();
            }
        }).showTwoSelectData("主人", R.mipmap.img_idcard_fail_dialog, "只有认证成功才能借款啊，您确定要离开吗？", "残忍离开", "我要留下");
        txtTitle.setText("常用联系人");
        selectMenuDilaog = new SelectMenuDilaog(this);
        dataOne = new ArrayList<>();
        dataOne.add("父母");
        dataOne.add("配偶");

        dataTwo = new ArrayList<>();
        dataTwo.add("兄弟");
        dataTwo.add("姐妹");

        selectMenuDilaog.setOnChooseListener(new SelectMenuDilaog.OnChooseListener() {
            @Override
            public void onSuccess(int poi, String text, String type) {
                if (selectRelative == 0) {
                    txtRelativeOne.setText(text);
                } else {
                    txtRelativeTwo.setText(text);
                }
            }
        });
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void checkContactPermission(final Intent intent, final int result) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                startActivityForResult(intent, result);
            }

            @Override
            public void onReject() {

            }


        }, R.string.contact_p, R.string.get_contact, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS);
    }

    public String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
//            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 300) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = getPhoneContacts(uri);
            if (contacts == null) {
                ToastUtil.makeText(this, "请开启读取联系人权限").show();
                return;
            }
            if (TextUtils.isEmpty(contacts[1].replace(" ", ""))) {
                ToastUtil.makeText(this, "联系人电话为空或未开启读取联系人权限").show();
                return;
            }
//                    去除空格，否者传上去格式有误
// 姓名           txtRelativeTwoContent.setText(contacts[0].replace(" ", ""));
//     手机号       txtRelativeThreeContent.setText(contacts[1].replace(" ", ""));
            if (selectContact == 0) {
                relativesBean1.mobile = contacts[1].replace(" ", "");
                relativesBean1.name = contacts[0].replace(" ", "");

                txtNameOne.setText(contacts[0].replace(" ", ""));
                txtPhoneOne.setText(contacts[1].replace(" ", ""));
//                txtContactOne.setText(contacts[0].replace(" ", "") + contacts[1].replace(" ", ""));
            } else {
                relativesBean2.mobile = contacts[1].replace(" ", "");
                relativesBean2.name = contacts[0].replace(" ", "");
                txtNameTwo.setText(contacts[0].replace(" ", ""));
                txtPhoneTwo.setText(contacts[1].replace(" ", ""));
//                txtContactTwo.setText(contacts[0].replace(" ", "") + contacts[1].replace(" ", ""));
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.txt_name_one, R.id.txt_phone_one, R.id.txt_name_two, R.id.txt_phone_two, R.id.layout_area, R.id.btn_contact_two, R.id.layout_relative_one, R.id.btn_contact_one, R.id.layout_relative_two, R.id.cb_check, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_area:
                bottomDialog.show();
                break;
            case R.id.layout_relative_one:
                selectRelative = 0;
                selectMenuDilaog.setData(dataOne);
                selectMenuDilaog.show();
                break;
            case R.id.txt_phone_one:
            case R.id.txt_name_one:
            case R.id.btn_contact_one:
                selectContact = 0;
                Uri uri1 = ContactsContract.Contacts.CONTENT_URI;
                Intent contactIntent1 = new Intent(Intent.ACTION_PICK, uri1);
                checkContactPermission(contactIntent1, 300);
                break;

            case R.id.layout_relative_two:
                selectRelative = 1;
                selectMenuDilaog.setData(dataTwo);
                selectMenuDilaog.show();
                break;
            case R.id.txt_name_two:
            case R.id.txt_phone_two:
            case R.id.btn_contact_two:
                selectContact = 1;
                Uri uri2 = ContactsContract.Contacts.CONTENT_URI;
                Intent contactIntent2 = new Intent(Intent.ACTION_PICK, uri2);
                checkContactPermission(contactIntent2, 300);
                break;
            case R.id.cb_check:
                isAgree = !isAgree;
                if (isAgree) {
                    cbCheck.setImageResource(R.mipmap.img_step_check);
                } else {
                    cbCheck.setImageResource(R.mipmap.img_step_uncheck);
                }
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(addressInfo.province)) {
                    ToastUtil.makeText(this, "请选择所在地区");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editAddress))) {
                    ToastUtil.makeText(this, "请填写详细地址");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtNameOne))) {
                    ToastUtil.makeText(this, "请选择第一个联系人");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtRelativeOne))) {
                    ToastUtil.makeText(this, "请选择与联系人关系");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtNameTwo))) {
                    ToastUtil.makeText(this, "请选择第二个联系人");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtRelativeTwo))) {
                    ToastUtil.makeText(this, "请选择与联系人关系");
                    return;
                }
                if (UI.toString(txtNameOne).equals(UI.toString(txtNameTwo))) {
                    ToastUtil.makeText(this, "不能选择同一个联系人");
                    return;
                }
                if (!isAgree) {
                    ToastUtil.makeText(this, "请勾选同意");
                    return;
                }
                relativesBean1.relationship = UI.toString(txtRelativeOne);
                relativesBean2.relationship = UI.toString(txtRelativeTwo);
                addressInfo.address = UI.toString(editAddress);
                getSubmitAddress(addressInfo, relativesBeen);


                break;
        }
    }

    private void getSubmitAddress(AddressAddV3Bean.AddressBean addressInfo, List<AddressAddV3Bean.RelativesBean> relativesBeen) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        AddressAddV3Bean bean = new AddressAddV3Bean();
        bean.address = addressInfo;
        bean.relatives = relativesBeen;
        Api.api_service.getSubmitAddress(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "认证成功");
                    finish();
                });
    }


    @Override
    public void onBackPressed() {
        selectMenuTipsDilaog.show();
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        selectMenuTipsDilaog.show();
    }


    /**
     * 上传手机信息
     */
    private void getAddResslist() {
        phoneInfo.getCallLogList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                callLogList = (List<Map<String, String>>) o;
                submitData();
            }

            @Override
            public void onFailure(String cause) {
                submitData();
            }
        });
    }

    private void submitData() {
//        api.addResslist(PreferenceUtils.getString(this, "deal_id", ""), contactList, callLogList, appList, smsList);
    }

    /**
     * 获取通讯录
     */
    private void checkContactsPermission() {

        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                loadingDialog.show();
                phoneInfo.getContactsList(new InfoCallBack() {
                    @Override
                    public void onSuccess(final Object o) {
                        contactList = (List<Map<String, String>>) o;
//                        checkCallPermission();
                        getAppList();
                    }

                    @Override
                    public void onFailure(String cause) {
                        getAppList();
                    }
                });
            }

            @Override
            public void onReject() {

            }
        }, R.string.contact_p_v2, R.string.get_contact_v2, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS, Manifest.permission.READ_SMS, Manifest.permission.READ_CALL_LOG);
    }

    public void goAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(localIntent);
    }


    /**
     * 获取app列表
     */
    private void getAppList() {
        phoneInfo.getAppList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                appList = (List<Map<String, String>>) o;
                getSmsList();
//                getAddResslist();
            }

            @Override
            public void onFailure(String cause) {
//                getAddResslist();
                getSmsList();
            }
        });
    }

    /**
     * 获取短信列表
     */
    private void getSmsList() {
        phoneInfo.getSmsList(new InfoCallBack() {
            @Override
            public void onSuccess(final Object o) {
                smsList = (List<Map<String, String>>) o;
                getAddResslist();
            }

            @Override
            public void onFailure(String cause) {
                getAddResslist();
            }
        });
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        String s =
                (province == null ? "" : province.name) +
                        (city == null ? "" : city.name) +
                        (county == null ? "" : county.name) +
                        (street == null ? "" : street.name);

        if (province != null) {
            this.province = province.name;
        }
        if (city != null) {
            this.city = city.name;
        }
        if (county != null) {
            if (street != null) {
                area = county.name + street.name;
            } else {
                area = county.name;
            }
        }
        addressInfo.province = this.province;
        addressInfo.city = this.city;
        addressInfo.area = this.area;
        txtArea.setText(s);
        bottomDialog.dismiss();
    }
}
